﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _01.单例模式
{
    public sealed class Counter
    {
        public Counter()
        {
            CreateTime = DateTime.Now;
            Console.WriteLine($"实例化时间:{CreateTime}");
        }

        public DateTime CreateTime { get; set; }

        private static Counter singleton = null;

        //第一种：只能适应单线程
        /*public static Counter GetSingleton()
        {
             if(singleton == null )
            {
                singleton = new Counter();
            }
             return singleton;
        }*/

        //第二种：可以适应多线程
        //public static Counter Instance = new Counter();

        //第三种 加锁，性能差
        private static readonly object locker = new object();
        public static Counter Singleton
        {
            get
            {
                lock (locker)
                {
                    if (singleton == null)
                    {
                        singleton = new Counter();
                    }
                    return singleton;
                }
            }
        }
         
        //第四种 双判断锁 加强性能
        public static Counter Singleton2
        {
            get
            {
                if(singleton == null)
                {
                    lock(locker)
                    {
                        if(singleton == null)
                        {
                            singleton = new Counter();
                        }
                    }
                }
                return singleton;
            }
        }

        //第五种 Lazy 懒加载
        private static readonly Lazy<Counter> lazyInstance = new Lazy<Counter>(() => new Counter());
        public static Counter LazyInstance => lazyInstance.Value;

        //第六种 IOC容器进行单例注册  prism

         
    }
}
